export default class GxlTableSheet  {
  constructor(title, data) {
    this.id = new Date().getTime();
    this.title = title;
    this.fixedRowIndex = undefined;
    this.fixedCellIndex = undefined;
    this.selectedCells = [0];
    this.selectedRows = [0];
    //default show rows
    this.defaultShowRowCount = 100;
    this.defaultShowCellCount = 30;
    this.selectedRects=[]
    //the sheet data
    this.setData(data);
  }
  setSelected(rowIndexs,cellIndexs){
    this.selectedCells=cellIndexs||[]
    this.selectedRows=rowIndexs||[]
    return this
  }
  setFixedRow(rowIndex) {
    this.fixedRowIndex = rowIndex
    return this
  }
  setFixedCell(cellIndex) {
    this.fixedCellIndex = cellIndex
    return this
  }
  setTitle(title = "untitled") {
    this.title = title;
    return this
  }
  getMaxValue(arr) {
    let len = arr.length;
    let max = parseInt(arr[0]);
    while (len--) {
      const next = parseInt(arr[len]);
      if (next > max) {
        max = next;
      }
    }
    return max;
  }
  setSelectedRect(rects){
    this.selectedRects =rects
    return this
  }
  setData(data) {
    this.rows = data || {};
    const rowIndexs = Object.keys(this.rows);
    const maxRowIndex = this.getMaxValue(rowIndexs);
    if (maxRowIndex > this.defaultShowRowCount) {
      this.defaultShowRowCount = maxRowIndex + 50;
    }
    let maxCellIndex = 0
    rowIndexs.forEach(k => {
      const row = this.rows[k];
      const cells = row.cells;
      const cellIndexs = Object.keys(cells);
      const _maxCellIndex = this.getMaxValue(cellIndexs);
      if (_maxCellIndex > maxCellIndex) {
        maxCellIndex = _maxCellIndex
      }
    })
    if (maxCellIndex > this.defaultShowCellCount) {
      this.defaultShowCellCount = maxCellIndex + 10;
    }
  }

  saveCell(rowIndex, cellIndex, data) {
    const row = this.getRow(rowIndex);
    if (!row) {
      row = new GxlTableSheetRow(rowIndex);
      this.setRow(rowIndex, row);
    }
    const cell = row.getCell(cellIndex);
    if (!cell) {
      cell = new GxlTableSheetRowCell(cellIndex);
      row.setCell(cellIndex, cell);
    }
    const isDataObj = typeof data == "object";
    cell.value = isDataObj ? data.value || "" : data;
    if (isDataObj) {
      cell.settings = { ...cell.settings, ...data.settings };
    }
  }
  getRow(rowIndex) {
    return this.rows[rowIndex]
  }

  setRow(rowIndex, rowData) {
    this.rows[rowIndex] = rowData
  }
}

class GxlTableSheetRow {
  constructor(index, data) {
    this.cells = data || {};
    this.rowIndex = index;
    this.settings = {};
  }
  getCell(cellIndex) {
    return this.cells[cellIndex];
  }
  setCell(cellIndex, cellData) {
    this.cells[cellIndex] = cellData
  }
}

class GxlTableSheetRowCell {
  constructor(index, value) {
    this.value = value || "";
    this.cellIndex = index;
    this.settings = {
      type: "text",
      format: undefined,
      validate: undefined,
      cellStyle: {},
      colSpan: 0,
      rowSpan: 0,
    };
  }
}
